<?php
/**
 * Created by PhpStorm OF yuyi.
 * User: YUYI
 * Date: 2018/5/16 0016
 * Time: 上午 11:39
 * Administrator
 */

namespace app\index\controller;


use app\common\controller\Base;
use app\common\model\Articles;
use app\common\service\ArticleService;
use app\common\service\UserService;
use think\Request;

class Article extends Base
{
    protected $isPublic = 'index';

    /**
     * 显示文章
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $id = input('id');
        $article = Articles::get($id,['User','Comments']);
        if (!$article){
            $this->error('未找到此文章！');
        }
        ArticleService::getHotArticle();
        trace($article->getData('status'));
        if ($article->getData('status') == 99){
            $this->assign('article',$article);
        }else{
            $this->error('未找到此文章！');
        }
        $article->setInc('countBrowses');
        return $this->fetch();
    }

    /**
     * 点赞成功
     * @param $id
     * @return string
     */
    public function laud($id)
    {
        $art = Articles::get($id);
        if (!$art){
            $this->error('非法访问');
        }
        $r = $art->setInc('countLauds');
        if ($r){
            $r = $art->find();
            return $this->successInfo('成功',['Lauds'=>$r->countLauds]);
        }else{
            return $this->errorInfo('失败');
        }
    }

    /**
     * 添加文章
     */
    public function add()
    {
        $data = input();
        $data['userId'] = 1;//UserService::getCurrentUserInfo()['userid'];
        preg_match_all('/[a-zA-z]+:[\/]{2}[^\s]*[.]{1}((jpg)|(png)|(gif))/',$data['content'],$arr);
        if ($arr){
            $data['articlePicPath'] = $arr[0];
        }
        $r = Articles::create($data);
        if ($r){
            $this->redirect('/index/admin/articleList');
        }else{
            $this->error('您的文章保存失败。');
        }
    }

    /**
     * 修改文章
     * @return string
     */
    public function modify()
    {
        $id = input('id');
        if (!$id){
            $this->error('非法访问');
        }
        $art = Articles::get($id);
        $r = $art->save(['title'=>input('title'),'content'=>input('content'),'status'=>10]);
        if ($r){
            if ($this->request->isAjax())
                return $this->successInfo('成功修改');
            else{
                $this->success('成功修改');
            }
        }else{
            if ($this->request->isAjax())
                return $this->errorInfo('修改失败');
            else{
                $this->error('修改失败');
            }
        }
    }

    /**
     * 删除文章
     */
    public function del()
    {
        $id = input('id');
        if (!$id){
            $this->error('非法访问');
        }
        $r = Articles::destroy($id);
        if ($r){
            $this->success('成功删除此文章！');
        }else{
            $this->error('无法删除此文章！');
        }
    }
}